package com.twu.biblioteca.ui;

import com.twu.biblioteca.data.BookDAO;

import java.io.InputStream;
import java.util.Scanner;

/**
 * Created by florian on 26/12/13.
 */
public class BibliotecaUIController {

    private final InputStream in;
    private final Scanner scanner;
    private BibliotecaUI ui;
    private ScreenController state;
    private BookDAO bookDAO;
    public BibliotecaUIController(BibliotecaUI ui,BookDAO bookDAO,InputStream in) {
        this.ui = ui;
        this.in = in;
        this.scanner = new Scanner(in);
        this.state = new ScreenControllerFactory(ui,bookDAO).createMainScreenController();
        this.bookDAO = bookDAO;
    }

    public void startControlLoop() {
        ui.showWelcomeMessage();
        ui.listBooks(bookDAO.getAllAvailableBooks());
        ui.showMenu();

        while (next());
    }

    public boolean next() {
        if (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            return processCommand(line);
        }else {
            return false;
        }
    }

    private boolean processCommand(String line) {
        state = state.processCommand(line);
        return state != null;
    }

}
